<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row>
      <el-row>
        <el-card v-if="!detailVisible">
          <div slot="header">
            <span>{{
              this.$route.query.role_id === undefined ? '新增角色' : '编辑角色'
            }}</span>
          </div>
          <el-form
            :model="roleForm"
            :rules="roleFormRules"
            ref="roleFormRef"
            class="roleFormClass"
            label-width="100px"
          >
            <el-form-item label="角色名称" prop="role_name">
              <el-input
                v-model="roleForm.role_name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input
                v-model="roleForm.remark"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card v-if="detailVisible">
          <div slot="header">
            <span>{{ detailInfo.role_name }}</span
            >&nbsp;&nbsp;&nbsp;&nbsp;
            <span style="color: blue">{{
              detailInfo.active == 1 ? '已开启' : '已禁用'
            }}</span>
          </div>
          <el-descriptions>
            <el-descriptions-item label="角色名称">{{
              detailInfo.role_name
            }}</el-descriptions-item>
            <el-descriptions-item label="角色描述">{{
              detailInfo.remark
            }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{
              detailInfo.creator
            }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-row>
      <el-row v-if="detailVisible">
        <el-button
          v-if="detailInfo.active == 1"
          class="theme-background-color"
          @click="disable(detailInfo.role_id)"
          >禁用</el-button
        >
        <el-button
          v-if="detailInfo.active == 0"
          class="theme-background-color"
          @click="enable(detailInfo.role_id)"
          >启用</el-button
        >
        <el-button class="theme-background-color" @click="detailVisible = false"
          >编辑</el-button
        >
      </el-row>
      <el-row>
        <el-card>
          <div slot="header">
            <span>权限配置</span>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="isCheckAll"
              @change="handleCheckAllChange($event)"
              style="font-weight: bold"
              >全选</el-checkbox
            >
          </div>
          <!-- 一级权限 -->
          <div
            v-for="(item1, i1) in rightsAllData"
            :key="i1"
            :class="[i1 === 0 ? '' : 'bdtop', 'bdLR', 'bgcolor']"
            style="margin-bottom: 10px"
            ref="allRightsCheckboxRef"
          >
            <el-checkbox
              style="font-weight: bold"
              @change="handleCheckedFirstLevelAllChange(i1, $event)"
              v-model="item1.selected"
              :key="item1.id"
              :indeterminate="item1.isIndeterminate"
            >
              {{ item1.authName }}
            </el-checkbox>
            <!-- 二级权限 -->
            <div
              v-for="(item2, i2) in item1.children"
              :key="i2"
              :class="['bdtop', 'whitecolor']"
            >
              <span style="margin-left: 40px"></span>
              <el-checkbox
                style="font-weight: bold"
                v-model="item2.selected"
                @change="
                  handleCheckedSecondLevelChange(i1, i2, item2.id, $event)
                "
                :key="item2.id"
                :indeterminate="item2.isIndeterminate"
              >
                {{ item2.authName }}
              </el-checkbox>
              <!-- 三级权限 -->
              <!-- <br /><span>操作权限</span><br /> -->
              <div
                :class="[item2.children ? 'bdtop' : '']"
                style="display: flex"
              >
                <span class="spanOperate" v-show="item2.children"
                  >操作权限</span
                >
                <div v-for="(item3, i3) in item2.children" :key="i3">
                  <el-checkbox
                    v-model="item3.selected"
                    @change="
                      handleCheckedThirdLevelChange(
                        i1,
                        i2,
                        item2.id,
                        item3.id,
                        $event
                      )
                    "
                    :key="item3.id"
                  >
                    {{ item3.authName }}
                  </el-checkbox>
                </div>
              </div>
            </div>
          </div>
          <el-row v-if="!detailVisible">
            <el-button>取消</el-button>
            <el-button class="theme-background-color" @click="saveAllData"
              >保存</el-button
            >
          </el-row>
        </el-card>
      </el-row>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleForm: {
        roleName: '',
        remark: ''
      },
      roleFormRules: {
        roleName: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      rightsAllData: [],

      //   一级权限变量
      isIndeterminate: false,
      isCheckAll: false,

      // 详情页数据
      detailVisible: false,
      detailInfo: { roleName: '', status: '', roleDesc: '', id: '' }
    }
  },
  created() {
    console.log(this.$route.query)
    if (this.$route.query !== undefined) {
      // this.roleForm.name = this.$route.query.roleName
      // this.roleForm.desc = this.$route.query.roleDesc
      // this.rightsAllData = this.$route.query.children
      this.getRoleDataById()
      if (this.$route.query.detailVisible !== undefined) {
        this.detailVisible = true
      }
    }
    // else {
    this.getAllRightsData()
    // }
    // console.log(this.rightsAllData)
  },
  methods: {
    async getAllRightsData() {
      // 获取所有权限的数据
      // this.$route.query.id
      const { data: res } = await this.$http.post('/admin/role/selAuth', {
        role_id: this.$route.query.role_id
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      //   把获取到的权限数据保存到 data 中
      this.rightsAllData = res.data
    },
    // 全选事件
    handleCheckAllChange(e) {
      var childrenArray = this.rightsAllData
      this.checkLow(childrenArray, e)

      this.isIndeterminate = false
    },
    // 一级change事件
    handleCheckedFirstLevelAllChange(index, e) {
      //   console.log(index)
      console.log(e)
      // 一级勾选后，子级全部勾选或者取消
      this.rightsAllData[index].selected = e
      //   去掉一级不确定状态
      this.rightsAllData[index].isIndeterminate = false
      var childrenArray = this.rightsAllData[index].children
      //   console.log(childrenArray)
      this.checkLow(childrenArray, e)
      this.getIsCheckAll()
    },
    getIsCheckAll() {
      var tickCount = 0
      var unTickCount = 0
      var indeterminateCount = 0
      var ArrLength = this.rightsAllData.length
      for (var j = 0; j < ArrLength; j++) {
        // 全选checkbox状态
        if (this.rightsAllData[j].selected === true) tickCount++
        if (this.rightsAllData[j].selected === false) unTickCount++
        if (this.rightsAllData[j].isIndeterminate === true) indeterminateCount++
      }

      if (tickCount === ArrLength) {
        // 全选勾选
        this.isCheckAll = true
        this.isIndeterminate = false
      } else if (unTickCount === ArrLength) {
        // 全选不勾选
        this.isCheckAll = false
        if (indeterminateCount > 0) {
          this.isIndeterminate = true
        } else {
          this.isIndeterminate = false
        }
      } else {
        this.isCheckAll = false
        // 添加全选不确定状态
        this.isIndeterminate = true
      }
    },
    // 二级change事件
    handleCheckedSecondLevelChange(firstIndex, secondIndex, secondId, e) {
      // 处理一级框
      var higherArray = this.rightsAllData[firstIndex]
      this.checkHigherCheckbox(higherArray, secondId, e)
      //   全选框
      this.getIsCheckAll()

      // 三级框
      var childrenArray = higherArray.children[secondIndex].children
      this.checkLow(childrenArray, e)
    },
    // 三级change事件
    handleCheckedThirdLevelChange(
      firstIndex,
      secondIndex,
      secondId,
      thirdId,
      e
    ) {
      //   二级框
      var higherArray = this.rightsAllData[firstIndex].children[secondIndex]
      this.checkHigherCheckbox(higherArray, thirdId, e)

      // 一级框
      var higherArray2 = this.rightsAllData[firstIndex]
      // setTimeout(() => {
      this.checkHigherCheckbox(higherArray2, secondId, higherArray.selected)
      // }, 1000)
      //   全选框
      this.getIsCheckAll()
    },
    // 根据当前级别级权限的选择状态，判断上级权限是否选中
    checkHigherCheckbox(higherArray, nowId, e) {
      var childrenArray = higherArray.children
      var tickCount = 0
      var unTickCount = 0
      var indeterminateCount = 0
      var len = childrenArray.length
      for (var i = 0; i < len; i++) {
        if (nowId === childrenArray[i].id) childrenArray[i].selected = e
        if (childrenArray[i].selected === true) tickCount++
        if (childrenArray[i].selected === false) unTickCount++
        if (childrenArray[i].isIndeterminate === true) indeterminateCount++
      }
      // console.log('当前的ID：' + nowId)
      // console.log('选中的：' + tickCount)
      // console.log('未选中的：' + unTickCount)
      // console.log('半选状态的：' + indeterminateCount)
      if (tickCount === len) {
        // 一级全勾选
        higherArray.selected = true
        higherArray.isIndeterminate = false
      } else if (unTickCount === len) {
        // 一级级全不勾选
        higherArray.selected = false
        if (indeterminateCount > 0) {
          higherArray.isIndeterminate = true
        } else {
          higherArray.isIndeterminate = false
        }
      } else {
        higherArray.selected = false
        // 添加一级不确定状态
        higherArray.isIndeterminate = true
      }
      // console.log('当前父节点：' + higherArray)
      // console.log('当前父节点的选中状态：' + higherArray.selected)
      // console.log('当前父节点的半选状态：' + higherArray.isIndeterminate)
    },
    // 勾选下级
    checkLow(childrenArray, e) {
      if (childrenArray) {
        for (var i = 0, len = childrenArray.length; i < len; i++) {
          childrenArray[i].isIndeterminate = false
          childrenArray[i].selected = e
          if (childrenArray[i].children) {
            this.checkLow(childrenArray[i].children, e)
          }
        }
      }
    },
    saveAllData() {
      this.$refs.roleFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        // console.log(this.roleForm)
        console.log(this.rightsAllData)
        console.log(this.checkedData(this.rightsAllData))
        var rights = this.checkedData(this.rightsAllData)
        // console.log()
        var url = ''

        if (
          this.$route.query.role_id === '' ||
          this.$route.query.role_id === undefined
        ) {
          url = '/admin/role/add'
        } else {
          url = '/admin/role/edit'
          this.roleForm.role_id = this.$route.query.role_id
        }
        // var params = this.roleForm + { rights: rights }
        const { data: res } = await this.$http.post(url, {
          role: this.roleForm,
          rights: rights
        })

        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/system/roles')
      })
    },
    // 循环树，找选中checkbox的值
    checkedData(data, arr = []) {
      var length = data.length
      for (let i = 0; i < length; i++) {
        if (data[i].selected === true || data[i].isIndeterminate === true) {
          // arr.push(data[i].id)
          for (let j = 0; j < data[i].children.length; j++) {
            if (
              data[i].children[j].selected === true ||
              data[i].children[j].isIndeterminate === true
            ) {
              const item = {}
              item.gid = data[i].children[j].id
              if (
                data[i].children[j].selected === true ||
                data[i].children[j].isIndeterminate === true
              ) {
                const threeData = data[i].children[j].children
                var str = ''
                for (let k = 0; k < threeData.length; k++) {
                  if (threeData[k].selected === true) {
                    str += threeData[k].authName + ','
                  }
                }
                item.tags = str.substring(0, str.length - 1)
                item.dataScope = 'NONE'
              }
              arr.push(item)
            }
          }
        }
        // if (data[i].children) {
        //   this.checkedData(data[i].children, arr)
        // }
      }
      return arr
    },
    async disable(id) {
      // 弹框询问是否禁用用户
      const confirmResult = await this.$confirm(
        '禁用后将无法登陆及使用系统，是否确认禁用该用户？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      // const { data: res } = await this.$http.post(
      //   'removeProductById', {
      //   idi : id
      // }
      // )
      const { data: res } = await this.$http.post('/admin/role/active', {
        role_id: id
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.detailInfo.active = 0
    },
    async enable(id) {
      // 弹框询问是否启用用户
      const confirmResult = await this.$confirm(
        '是否确认启用该用户？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      // const { data: res } = await this.$http.post(
      //   'removeProductById', {
      //   idi : id
      // }
      // )
      const { data: res } = await this.$http.post('/admin/role/active', {
        role_id: id
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.detailInfo.active = 1
    },
    async getRoleDataById() {
      this.detailInfo = this.$route.query
      this.roleForm = this.detailInfo
    }
  }
}
</script>

<style lang="less" scoped>
.roleFormClass {
  width: 500px;

  .el-select {
    width: 400px !important;
  }
}
.el-row {
  margin-bottom: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdLR {
  border: 1px solid #eee;
}
.el-checkbox {
  margin: 10px;
}
.bgcolor {
  background-color: #f5f5f5;
}
.whitecolor {
  background-color: #fff;
}
.spanOperate {
  margin: 0 5px 0 50px;
  color: #797979;
  font-size: 14px;
  line-height: 40px;
}
</style>
